package java_thinking.unit_21.Exercise.thread.pool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @Desc:   把Callable实例当作参数，生成一个FutureTask的对象，然后把这个对象当作一个Runnable，作为参数另起线程。
 *          由于FutureTask实现了Runnable，因此它既可以通过Thread包装来直接执行，也可以提交给ExecuteService来执行。
 * @author: cww
 * @DateTime: 2019-08-04 20:33
 */

public class FutureTaskCallableTest {
    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
    private static ThreadPoolExecutor executors = new ThreadPoolExecutor(4,8,5000,TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(1000),namedThreadFactory,new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
//        Callable<Integer> call = () -> {
//            System.out.println("call thread started");
//            Thread.sleep(5000);
//            return 3333;
//        };
//        FutureTask<Integer> task = new FutureTask<>(call);
//        Thread thread = new Thread(task);
//        thread.start();
//        System.out.println("do something else");
//        try {
//            System.out.println("get Result from future : " + task.get());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
        calculate();

    }


    public static void calculate(){
        Callable<Integer> call = () -> {

            System.out.println(Thread.currentThread().getName()+" 执行方法");
            Thread.sleep(3000);
            return 10;
        };
        Future<Integer> result = new FutureTask<>(call);
//        Thread thread = new Thread((Runnable) result);
//        Runnable run = new Runnable() {
//            @Override
//            public void run() {
//                ((FutureTask<Integer>) result).run();
//            }
//        };
        executors.execute((Runnable) result);
        try {

            Integer i = result.get();
            System.out.println(Thread.currentThread().getName()+ " " +i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
